package com.wd.elec.server;


import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import java.net.DatagramPacket;
import java.net.DatagramSocket;


/**
 * @className: UDPServer
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/6/29
 **/


@Component
@EnableAsync
public class UDPServer {

    @Async
    public void startServer() {
        System.out.println("===============================================");
        System.out.println("begin to start server!");
        try (DatagramSocket socket = new DatagramSocket(8200)) { // 绑定在端口9876上
            byte[] buffer = new byte[1024];
            while (true) {
                DatagramPacket incomingPacket = new DatagramPacket(buffer, buffer.length);
                socket.receive(incomingPacket);

                // 处理接收到的数据
                String message = new String(incomingPacket.getData(), 0, incomingPacket.getLength());
                System.out.println("Received message: " + message);

                // 可以在这里加入业务逻辑，如根据收到的消息发送响应等

                // 清空缓冲区，以便下一次接收
                buffer = new byte[1024];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
